package moni.anyou.com.view.view;

import android.annotation.TargetApi;
import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.RelativeLayout;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.readystatesoftware.systembartint.SystemBarTintManager;
import com.tencent.imsdk.TIMConnListener;
import com.tencent.imsdk.TIMConversationType;
import com.tencent.imsdk.TIMManager;
import com.tencent.qcloud.timchat.model.FriendshipConversation;
import com.tencent.qcloud.timchat.ui.ChatActivity;

import org.apache.http.HttpEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.FormBodyPart;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.ContentBody;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.params.HttpParams;
import org.kymjs.aframe.http.HttpCallBack;
import org.kymjs.aframe.http.I_HttpParams;
import org.kymjs.aframe.http.KJHttp;
import org.kymjs.aframe.http.KJStringParams;
import org.kymjs.aframe.http.StringCallBack;
import org.kymjs.aframe.utils.FileUtils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import me.lxz.photopicker.camera.Mode;
import me.lxz.photopicker.camera.OnPhotoPickFinsh;
import me.lxz.photopicker.camera.PictureSelector;
import me.lxz.photopicker.tools.PictureUtil;
import moni.anyou.com.view.R;
import moni.anyou.com.view.base.BaseActivity;
import moni.anyou.com.view.config.SysConfig;
import moni.anyou.com.view.tim.TimSplashStart;
import moni.anyou.com.view.tool.PermissionTools;
import moni.anyou.com.view.tool.ToastTools;
import moni.anyou.com.view.utils.KJHttpBuild;
import moni.anyou.com.view.view.account.LoginActivity;
import moni.anyou.com.view.view.my.RomUtils;
import moni.anyou.com.view.view.my.RouteTeamActivity;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class IndexActivity extends BaseActivity  {


    public static final String Position_Key = "position_key";
    public static int position = 0;
    public static IndexActivity getInstance = null;
    private RadioGroup mRadioGroup;
    private IndexAdapter mFragmentAdapter;
    private List<Fragment> mFragmentList = new ArrayList<Fragment>();
    private KindergartenFragment mKindergartenFragment;
    private FabuFragment mFabuFragment;
    private DailyFragment mDailyFragment;
    private DynamicsFragment mDynamicsFragment;
    private MyFragment mMyFragment;
    private RadioButton radioRoute;
    private RadioButton radioFabu;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAndroidNativeLightStatusBar(this, true);
        MIUISetStatusBarLightMode(this, true);
        setFlymeLightStatusBar(this,true);
        initState();
        initWindow();
        requestWindowFeature(Window.FEATURE_NO_TITLE);
//        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
//                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        setContentView(R.layout.activity_index);


        init();

        LogOut.getInstance().addActivity(this);
        /**针对底部有软菜单的手机*/
        RadioGroup layout = (RadioGroup) findViewById(R.id.radio_main);
        RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) layout.getLayoutParams();
        lp.setMargins(0, 0, 0, getNavigationBarHeight());
        //if (!SysConfig.isIMLogin){
        //    TimSplashStart start = new TimSplashStart();
        //    start.onCreate(IndexActivity.this);
         //   start.imLogin();
        //}

        Intent serviceIntent=new Intent(this,ChatService.class);
        startService(serviceIntent);







    }

    //手机高版本样式
    private void initState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            /* 透明导航栏 */
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

    }

    private SystemBarTintManager tintManager;

    //手机高版本样式
    @TargetApi(19)
    private void initWindow() {


        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintColor(Color.TRANSPARENT);
            tintManager.setStatusBarTintEnabled(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                Class decorViewClazz = Class.forName("com.android.internal.policy.DecorView");
                Field field = decorViewClazz.getDeclaredField("mSemiTransparentStatusBarColor");
                field.setAccessible(true);
                field.setInt(getWindow().getDecorView(), Color.TRANSPARENT);  //改为透明
            } catch (Exception e) {
            }
        }

    }

    private static void setAndroidNativeLightStatusBar(Activity activity, boolean dark) {
        View decor = activity.getWindow().getDecorView();
        if (dark) {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
        } else {
            decor.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
        }
    }


    /**
     * 获取底部软键盘状态栏的高度 适配这种类型的手机
     */

    public int getNavigationBarHeight() {
        Resources resources = this.getResources();
        int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
        int height = resources.getDimensionPixelSize(resourceId);

        return height;

    }

    @Override
    public void initView() {
        super.initView();

        getInstance = this;
        mRadioGroup = (RadioGroup) findViewById(R.id.radio_main);
        radioRoute = (RadioButton) findViewById(R.id.radio_route);
        radioFabu = (RadioButton) findViewById(R.id.radio_fabu);
        mKindergartenFragment = new KindergartenFragment();
        mFabuFragment = new FabuFragment();
        mDynamicsFragment = new DynamicsFragment();
        mDailyFragment = new DailyFragment();
        mMyFragment = new MyFragment();

    }

    @Override
    public void setData() {
        super.setData();
        mFragmentList.add(mKindergartenFragment);
        mFragmentList.add(mFabuFragment);
        mFragmentList.add(mDailyFragment);
        mFragmentList.add(mDynamicsFragment);
        mFragmentList.add(mMyFragment);
        mFragmentAdapter = new IndexAdapter(IndexActivity.this, mFragmentList,
                R.id.index_main, mRadioGroup, 0);

        checkPosition(getIntent().getIntExtra(Position_Key, 0));
    }


    @Override
    public void onBack() {
        super.onBack();
        //activityAnimation(TOP_OUT);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        switch (keyCode) {
            case KeyEvent.KEYCODE_BACK:
                doExit(false);
                return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private boolean isExit = false;

    public void doExit(boolean skip) {
        if (!isExit && !skip) {
            isExit = true;
            ToastTools.showShort(mContext, "再按一次退出程序");
        } else {
            LogOut.getInstance().exit();
        }
    }

    public void checkPosition(int position) {
        switch (position) {
            case 0:
                IndexAdapter.currentTab = 0;
                findViewById(R.id.radio_kindergarden).performClick();
                break;
            case 1:
                IndexAdapter.currentTab = 1;
                findViewById(R.id.radio_fabu).performClick();

                break;
            case 2:
                IndexAdapter.currentTab = 2;
                findViewById(R.id.radio_route).performClick();
                break;
            case 3:
                IndexAdapter.currentTab = 3;
                findViewById(R.id.radio_dynamics).performClick();
                break;
            case 4:
                IndexAdapter.currentTab = 4;
                findViewById(R.id.radio_my).performClick();
                break;
            default:
                break;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if ((position > 0) && (position < 5)) {
            checkPosition(position - 1);
            position = 0;
        }


        // hui guen anniu zhuangtai
        if (radioRoute.isChecked()) {
            mRadioGroup.setOnCheckedChangeListener(null);
            radioRoute.setChecked(false);
            mRadioGroup.setOnCheckedChangeListener(mFragmentAdapter);
        }
        if (radioFabu.isChecked()) {
            mRadioGroup.setOnCheckedChangeListener(null);
            radioFabu.setChecked(false);
            mRadioGroup.setOnCheckedChangeListener(mFragmentAdapter);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        getInstance = null;
    }


    public static boolean MIUISetStatusBarLightMode(Activity activity, boolean dark) {
        boolean result = false;
        Window window = activity.getWindow();
        if (window != null) {
            Class clazz = window.getClass();
            try {
                int darkModeFlag = 0;
                Class layoutParams = Class.forName("android.view.MiuiWindowManager$LayoutParams");
                Field field = layoutParams.getField("EXTRA_FLAG_STATUS_BAR_DARK_MODE");
                darkModeFlag = field.getInt(layoutParams);
                Method extraFlagField = clazz.getMethod("setExtraFlags", int.class, int.class);
                if (dark) {
                    extraFlagField.invoke(window, darkModeFlag, darkModeFlag);
                    //状态栏透明且黑色字体
                } else {
                    extraFlagField.invoke(window, 0, darkModeFlag);//清除黑色字体
                }
                result = true;
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M &&
                        RomUtils.isMiUIV7OrAbove()) { //开发版 7.7.13 及以后版本采用了系统API，旧方法无效但不会报错，所以两个方式都要加上
                    if (dark) {
                        activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
                    } else {
                        activity.getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
                    }
                }
            } catch (Exception e) {
            }
        }
        return result;
    }


    private static boolean isFlymeV4OrAbove() {
        String displayId = Build.DISPLAY;
        if (!TextUtils.isEmpty(displayId) && displayId.contains("Flyme")) {
            String[] displayIdArray = displayId.split(" ");
            for (String temp : displayIdArray) { //版本号4以上，形如4.x. if (temp.matches("^[4-9]\\.(\\d+\\.)+\\S*"))
                {
                    return true;
                }
            }
        }
        return false;
    }


    private static boolean setFlymeLightStatusBar(Activity activity, boolean dark) {
        boolean result = false;
        if (activity != null) {
            try {
                WindowManager.LayoutParams lp = activity.getWindow().getAttributes();
                Field darkFlag = WindowManager.LayoutParams.class.getDeclaredField("MEIZU_FLAG_DARK_STATUS_BAR_ICON");
                Field meizuFlags = WindowManager.LayoutParams.class.getDeclaredField("meizuFlags");
                darkFlag.setAccessible(true);
                meizuFlags.setAccessible(true);
                int bit = darkFlag.getInt(null);
                int value = meizuFlags.getInt(lp);
                if (dark) {
                    value |= bit;
                } else {
                    value &= ~bit;
                }
                meizuFlags.setInt(lp, value);
                activity.getWindow().setAttributes(lp);
                result = true;
            } catch (Exception e) {
            }
        }
        return result;
    }




}
